package com.cy.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cy.bean.GameList;
import com.cy.bean.UserList;
import com.cy.service.BuyGameService;
import com.cy.service.BuyGameServiceImpl;

/**
 * Servlet implementation class BuyGameServlet
 */
@WebServlet("/buygame")
public class BuyGameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置前端页面传递回来的字符编码
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		int totalNum = 0;
		BuyGameService buyGameService = new BuyGameServiceImpl();
		String flag = request.getParameter("flag");
		// 返回搜索栏内的输入情况
		String namevalue = request.getParameter("gamename");
		if (namevalue == null || namevalue.equals("")) {
			// 输入框提示值
			request.setAttribute("query_tip", "请输入游戏名...");
			// 当没搜索时查找总条目数
			totalNum = buyGameService.findTotal();
		} else if (namevalue != null && !namevalue.equals("")) {
			request.setAttribute("query_tip", namevalue);
		}
		String page = request.getParameter("page");
		if (page == null || page.equals("")) {
			page = "0";
		}
		// 获取当前登录用户的id
		int nowid = ((UserList) request.getSession().getAttribute("gengraluser")).getId();
		List<GameList> games = buyGameService.findAllByPage(Integer.parseInt(page), namevalue,nowid);
		request.setAttribute("games", games);
		int totalPage = (totalNum % 8 == 0) ? totalNum / 8 : totalNum / 8 + 1;
		// 将总页数与当前页数传出去
		request.setAttribute("totalPage", totalPage);
		request.setAttribute("page", Integer.parseInt(page));
		request.setAttribute("flag", flag);
		request.setAttribute("mainRight", "/WEB-INF/jsp/buygame.jsp");
		request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);

	}

}
